import React, { useEffect, useRef } from "react";
import Viewer from 'viewerjs';

interface IProps {
  selector?: string
}
const ImgViewer: React.FC<IProps> = (props) => {
  const wrap = useRef(null);

  useEffect(() => {
    let dom = null;
    if (!props.selector) {
      dom = wrap.current;
    } else {
      dom = document.querySelector(`#${props.selector}`);
    }
    const viewer = new Viewer(dom as HTMLElement);
    // 监听dom的改变
    const observer = new MutationObserver(() => {
      viewer.update();
    });
    observer.observe(dom as HTMLElement, {
      subtree: true,
      childList: true
    })
    return () => {
      viewer.destroy();
      observer.disconnect();
    }
  }, [])

  return <div ref={wrap}>
    {props.children}
  </div>
}

export default ImgViewer;